<template>
  <div
    class="msgtpl-form-wrap"
    v-loading="loading">
    <div class="form-props">
      <el-form
        :model="form"
        ref="createForm"
        :rules="rules"
        class="form mp-form"
        label-width="80px"
      >
        <el-form-item label="模板编码" prop="msg_code">
          <el-input
            v-model="form.msg_code"
            autocomplete="off"
            :disabled="isView || isEdit"
            placeholder="模板唯一编码"
          />
        </el-form-item>
        <el-form-item label="模板名称" prop="msg_name">
          <el-input
            v-model="form.msg_name"
            autocomplete="off"
            :disabled="isView || isEdit"
            placeholder="模板中文名"
          />
        </el-form-item>
        <el-form-item label="消息类型" prop="type">
          <el-radio-group v-model="form.type" :disabled="isView || isEdit">
            <el-radio-button :label="4">微信模板消息</el-radio-button>
            <el-radio-button :label="1">Web消息</el-radio-button>
            <el-radio-button :label="2">短信</el-radio-button>
            <el-radio-button :label="3" disabled>邮件</el-radio-button>
          </el-radio-group>
          <el-form
            v-if="form.type === 4 || form.type === 2"
            label-position="top"
            class="innner-form"
          >
            <el-form-item
              :label="form.type === 4 ? '微信模板ID': '短信模板ID'"
              prop="wx_tpl_id"
            >
              <el-input
                v-model="form.wx_tpl_id"
                autocomplete="off"
                :disabled="isView || isEdit"
                :placeholder="form.type === 4 ? '微信模板ID，复制微信后台的模板ID': '短信模板ID'"
              />
            </el-form-item>
            <el-form-item
              v-if="form.type === 4"
              label="微信模板内容"
              prop="wx_tpl_content"
              style="margin-bottom: 0px;">
              <el-input
                v-model="form.wx_tpl_content"
                type="textarea" :rows="2"
                autocomplete="off"
                :disabled="isView"
                placeholder="微信模板消息内容体，复制微信后台的模板消息体"
              />
            </el-form-item>
          </el-form>
        </el-form-item>

        <el-form-item
          label="消息模板"
          prop="msg_data">
          <el-form
            v-if="form.type === 1"
            label-position="top"
            class="innner-form">
            <el-form-item
              label="消息标题（消息列表标题）"
              prop="msg_data.title">
              <el-input
                v-model="form.msg_data.title"
                type="textarea"
                :rows="2"
                autocomplete="off"
                :disabled="isView"
                placeholder="消息标题"
              />
            </el-form-item>
            <el-form-item
              label="消息内容（可选，进入页面后展示的详细内容）"
              prop="msg_data.content">
              <el-input
                v-model="form.msg_data.content"
                type="textarea"
                :rows="2"
                autocomplete="off"
                :disabled="isView"
                placeholder="消息内容"
              />
            </el-form-item>
            <el-form-item
              label="URL WEB链接"
              prop="msg_data.url">
              <el-input
                v-model="form.msg_data.url"
                type="textarea"
                :rows="2"
                autocomplete="off"
                :disabled="isView"
                placeholder="URL链接，无需带域名，如: /apps/jwpage/"
              />
            </el-form-item>
            <el-form-item label="URL H5链接" prop="msg_data.url_h5">
              <el-input
                v-model="form.msg_data.url_h5"
                type="textarea"
                :rows="2"
                autocomplete="off"
                :disabled="isView"
                placeholder="URL链接，无需带域名，如: /apps/jwh5/" />
            </el-form-item>
          </el-form>

          <el-form
            v-else-if="form.type === 3"
            label-position="top"
            class="innner-form">
            <el-form-item label="邮件标题" prop="msg_data.title">
              <el-input
                v-model="form.msg_data.title"
                type="textarea"
                :rows="2"
                autocomplete="off"
                :disabled="isView"
              />
            </el-form-item>
            <el-form-item label="邮件内容" prop="msg_data.content">
              <el-input
                v-model="form.msg_data.content"
                type="textarea"
                :rows="2"
                autocomplete="off"
                :disabled="isView"
              />
            </el-form-item>
          </el-form>

          <el-form
            v-else-if="form.type === 4 || form.type === 2"
            label-position="top"
            class="innner-form"
          >
            <el-form-item
              :label="form.type === 4 ? '消息内容（可选，进入页面后展示的详细内容）': '可选，不支持消息模板变量的短信内容'"
              prop="msg_data.content">
              <el-input
                v-model="form.msg_data.content"
                type="textarea"
                :rows="2"
                autocomplete="off"
                :disabled="isView"
                placeholder="消息内容"
              />
            </el-form-item>
            <el-form-item v-if="form.type === 4" label="URL链接" prop="msg_data.url">
              <el-input
                v-model="form.msg_data.url_h5"
                type="textarea"
                :rows="2"
                autocomplete="off"
                :disabled="isView"
                placeholder="URL链接，无需带域名，如: /apps/jwh5/"
              />
            </el-form-item>
            <p style="color: red;margin: 0px;font-size: 12px;">
              <template v-if="form.type === 4">属性名为微信模板消息内的变量名，如 {first.DATA}的 此处属性名为 first </template>
              <template v-else>短信模板内的变量</template>
            </p>
            <el-form label-width="60px">
              <template v-for="(wxItem, idx) in formWxDataItems" :key="idx">
                <div class="wx-data-item">
                  <JIcon
                    :icon="DFT_ICONS.close"
                    class="close-btn"
                    @click="handleRemoveWxDataItem(idx)"
                  />
                  <el-form-item label="属性名" style="margin-bottom: 0px;">
                    <el-input v-model="wxItem.name" placeholder="属性名"></el-input>
                  </el-form-item>
                  <el-form-item label="属性值">
                    <el-input
                      v-model="wxItem.value"
                      type="textarea"
                      :rows="2"
                      autocomplete="off"
                      :disabled="isView"
                      placeholder="属性值"
                    />
                  </el-form-item>
                </div>
              </template>
            </el-form>
            <div style="text-align:right;padding-right: 10px;">
              <el-button
                type="primary"
                plain
                size="small"
                @click="handleAddWxDataItem">
                <template #icon>
                  <JIcon :icon="DFT_ICONS.add" />
                </template>增加属性项</el-button>
            </div>
          </el-form>
        </el-form-item>

        <el-form-item v-if="isView">
          <el-button
            type="primary"
            @click="handleCustomCloseWin()"
          >确 定</el-button>
        </el-form-item>
      </el-form>
      <div class="attr-actions">
        <el-button
          type="primary"
          size="large"
          @click="handleSave()"
        >确 定</el-button>
        <el-button
          size="large"
          @click="handleCustomCloseWin()"
        >取 消</el-button>
      </div>
    </div>

    <div class="config-attrs">
      <el-tabs v-model="configActiveTab">
        <el-tab-pane v-for="t in tabs" :label="t.label" :name="t.name" :key="t.name">
          <el-row :gutter="10">
            <el-col v-for="rp in t.items" :span="8" :key="rp.name">
              <el-tag
                size="large"
                class="attr-tag"
                @click="handleCopyProp(rp, t)"
              >
                <b>{{ rp.label }}</b>
                <span style="float: right;">{{ rp.name }}</span>
              </el-tag>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup>
import _ from 'lodash'
import { ref, reactive, onMounted, watch, computed } from 'vue';
import {api} from "@jzl/api";
import {DFT_ICONS} from "@jzl/icons";

const DFT = {
  msg_code: '',
  msg_name: '',
  msg_remark: '',
  type: 4,
  wx_tpl_id: null,
  wx_tpl_content: null,
  msg_data: {
    _wx_keys: [],
    title: "",
    content: "",
    url_h5: "",
    url: ""
  }
};

// Props
const props = defineProps({
  tplId: [String, Number],
  tplForm: Object,
  formId: [String, Number]
});

// Emits
const emit = defineEmits(['close']);

// State
const loading = ref(false);
const form = ref(_.cloneDeep(DFT));
const formWxDataItems = ref([]);
const formInfo = ref(null);
const configActiveTab = ref('');
const tabs = ref([]);

const rules = ref({});

// Computed
const isView = computed(() => false); // 假设始终为 false，可根据业务扩展
const isEdit = computed(() => !!props.tplId);

// Methods
const init = async () => {
  loading.value = true;

  let tpl = null;
  let formWxDataItemsVal = [];

  if (props.tplId) {
    tpl = await api.msgtpl.getTpl(props.tplId);
    formWxDataItemsVal = getFormWxDataItems(tpl);
  } else {
    tpl = _.cloneDeep(DFT);
    tpl.msg_code = window.$utils.getNanoid(12);
  }

  form.value = tpl;
  formWxDataItems.value = formWxDataItemsVal;

  let formInfoVal = null;

  if (props.formId > 0) {
    if (props.tplForm && props.tplForm.form_id == props.formId) {
      formInfoVal = props.tplForm;
    } else {
      formInfoVal = await api.form.getFormById(props.formId);
    }
  }

  formInfo.value = formInfoVal;
  loading.value = false;

  let configActiveTabVal = "common";
  let tabsVal = [{
    type: 'self',
    name: "common",
    itemName: "common",
    label: '通用属性',
    items: [{
      type: "number",
      name: "_task_id",
      label: "审批任务ID"
    }, {
      type: "number",
      name: "_node_id",
      label: "流程节点ID"
    }, {
      type: "number",
      name: "_flow_instance_id",
      label: "流程实例ID"
    }, {
      type: "number",
      name: "_flow_id",
      label: "流程ID"
    }, {
      type: "input",
      name: "_form.form_name",
      label: "业务名称"
    }, {
      type: "input",
      name: "_input_param",
      label: "用户输入"
    }]
  }];

  if (formInfoVal) {
    const selfFormCode = _.get(formInfoVal, 'form_code');

    const self = {
      type: 'self',
      name: selfFormCode,
      label: '当前属性',
      items: []
    };

    const commonItems = [
      { type: 'number', label: '表单ID', name: '_form_id' },
      { type: 'number', label: '视图ID', name: '_view_id' }
    ];

    const isFlow = _.get(formInfoVal, 'use_type') === 'WORKFLOW';

    if (selfFormCode === "_ADMIN") {
      commonItems.push({ type: 'number', label: '数据ID', name: 'id' });
      commonItems.push({ type: 'number', label: '所属人昵称', name: 'nickname' });
    } else {
      commonItems.push({ type: 'number', label: '数据ID', name: '_data_id' });
      commonItems.push({ type: 'number', label: '数据所属人ID', name: '_owner_id' });
      commonItems.push({ type: 'number', label: '所属人昵称', name: '_owner_name' });
    }

    commonItems.push({ type: 'input', label: '所属人昵称/账号', name: '_ADMIN_ID__label' });

    if (isFlow) {
      commonItems.push({ type: 'number', label: '流程ID', name: '_flow_id' });
      commonItems.push({ type: 'number', label: '流程实例ID', name: '_flow_instance_id' });
    }

    self.items = commonItems;

    const items = _.get(formInfoVal, 'items');
    if (items && items.length) {
      for (let i = 0; i < items.length; i++) {
        const it = items[i];
        if (it.type === 'formrel') {
          const formCode = _.get(it, 'rel_code');
          const itemName = _.get(it, 'name');
          let name = `${it.type === 'formrel' ? '父' : '子'}:${it.label}`;
          if (it.form_item_code === '_ADMIN') name = '用户数据';

          if (formCode) {
            const form = await api.form.getFormByCode(formCode);
            const formdataItems = _.sortBy(_.filter(_.get(form, 'items'), it => {
              return it.type !== 'formdata' && it.type !== 'formrel_item';
            }), ['y', 'x']);
            tabsVal.push({
              type: it.type,
              name: itemName,
              itemName: itemName,
              label: name,
              items: formdataItems
            });
          }

          if (it.type !== 'formrel_item' && it.type !== 'formdata') {
            self.items.push(it);
          }
        } else if (it.type !== 'formrel_item' && it.type !== 'formdata') {
          self.items.push(it);
        }
      }
    }

    self.items = _.sortBy(self.items, ['y', 'x']);
    tabsVal.push(self);
    configActiveTabVal = selfFormCode;
  } else {
    const form = await api.form.getFormByCode("_ADMIN");
    const formdataItems = _.filter(_.get(form, 'items'), it => {
      return it.type !== 'formdata' && it.type !== 'formrel_item';
    });
    const userInfo = {
      type: 'formrel',
      name: "_owner",
      itemName: "_owner",
      label: '用户数据',
      items: formdataItems
    };
    tabsVal.push(userInfo);
  }

  tabs.value = tabsVal;
  configActiveTab.value = configActiveTabVal;
};

const getFormWxDataItems = (temp) => {
  const formWxDataItemsVal = [];
  const type = _.get(temp, 'type');

  if (type === 4 || type === 2) {
    const msgData = _.get(temp, 'msg_data');
    const _wx_keys = _.get(msgData, '_wx_keys');

    if (_wx_keys && _wx_keys.length) {
      for (let i = 0; i < _wx_keys.length; i++) {
        const key = _wx_keys[i];
        formWxDataItemsVal.push({
          name: key,
          value: msgData[key]
        });
      }
    }
  }

  return formWxDataItemsVal;
};

const handleSave = async () => {
  const formVal = _.cloneDeep(form.value);
  const tips = [];

  if (!formVal.msg_code) tips.push('编码不能为空！');
  if (!formVal.msg_name) tips.push('名称不能为空！');

  const msgData = _.get(formVal, 'msg_data');
  const type = _.get(formVal, 'type');
  const _wx_keys = [];

  if (type === 4 || type === 2) {
    if (!formVal.wx_tpl_id) tips.push(`${type === 4 ? '微信模板ID' : '短信模板ID'}不能为空！`);

    if (formWxDataItems.value && formWxDataItems.value.length) {
      for (let i = 0; i < formWxDataItems.value.length; i++) {
        const wxDataItem = formWxDataItems.value[i];
        if (wxDataItem && wxDataItem.name) {
          _wx_keys.push(wxDataItem.name);
          msgData[wxDataItem.name] = wxDataItem.value;
        }
      }
    }
  }

  msgData._wx_keys = _wx_keys;

  if (tips.length) {
    $jui.error({ message: tips.join('<br/>'), dangerouslyUseHTMLString: true });
    return;
  }

  if (!formVal.form_id) {
    formVal.form_id = props.formId;
  }

  formVal.msg_data = msgData;

  loading.value = true;

  const ret = formVal.id
    ? await api.msgtpl.updateTpl(formVal)
    : await api.msgtpl.createTpl(formVal);

  if (ret) {
    handleCustomCloseWin();
  }

  loading.value = false;
};

const handleCustomCloseWin = () => {
  emit('close');
};

const handleCopyProp = (prop, cate) => {
  let txt = '';
  if (cate.type === 'self') {
    txt = `{{${prop.name}}}`;
    if (prop.type === 'formrel') {
      txt = `{{${prop.name}__label}}`;
    }
  } else if (cate.type === 'formrel') {
    txt = `{{${cate.itemName}.${prop.name}}}`;
  }
  window.$utils.copyText(txt);
};

const handleAddWxDataItem = () => {
  formWxDataItems.value.push({ name: '', value: '' });
};

const handleRemoveWxDataItem = (idx) => {
  formWxDataItems.value.splice(idx, 1);
};

// Lifecycle
onMounted(() => {
  init();
});

// Watch
watch(
  () => [ props.formId, props.tplId],
  () => {
    init();
  }
);
</script>

<style lang="scss" scoped>
/* 样式保持不变 */
.msgtpl-form-wrap {
  display: flex;
  height: 100%;

  .form-props {
    width: 600px;
    display: flex;
    flex-flow: column;
    height: 100%;

    > form {
      flex: 1;
      overflow-y: auto;
      padding-right: 10px;
    }
  }

  .config-attrs {
    flex: 1;
    margin-right: 10px;
    height: 100%;
    overflow-y: auto;
  }

  .wx-data-item {
    border-top: 1px solid #EEE;
    padding-top: 10px;
    position: relative;

    .close-btn, .el-icon-close {
      position: absolute;
      padding: 2px;
      top: 0px;
      right: -20px;
      background: #FAFAFA;
      border-radius: 3px;

      &:hover {
        background: #EEE;
      }
    }
  }
}

.innner-form {
  padding: 10px;
  background: #FAFAFA;
  border-radius: 10px;
  margin-top: 10px;
  width:100%;
}
.attr-tag {
  width:100%;
  margin-bottom: 10px;
  cursor: pointer;
  position:relative;
}
.attr-actions {
  text-align:center;
  padding: 10px;
  border-top: 1px solid #F9F9F9;
}
</style>
